package org.zffc.boot.starter.vault.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.vault.core.VaultKeyValueOperations;
import org.springframework.vault.core.VaultKeyValueOperationsSupport;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.support.VaultResponse;

import java.util.Map;

@Component
public class VaultService {
    @Autowired
    private VaultTemplate vaultTemplate;

    /**
     * 读取指定路径的密钥值
     * @param path Vault 中的路径
     * @param key 键名
     * @return 对应的值
     */
    public String readValue(String path, String key) {
        VaultKeyValueOperations kvOperations = vaultTemplate.opsForKeyValue(path,VaultKeyValueOperationsSupport.KeyValueBackend.KV_1);
        VaultResponse response = kvOperations.get(key);
        if (response != null && response.getData() != null) {
            return (String) response.getData().get(key);
        }
        return null;
    }

    /**
     * 写入指定路径的密钥值 VaultKeyValueOperationsSupport.KeyValueBackend.KV_1 无版本化
     *
     * @param path Vault 中的路径
     * @param key 键名
     * @param value 要写入的值
     */
    public void writeValue(String path, String key, String value) {
        VaultKeyValueOperations kvOperations = vaultTemplate.opsForKeyValue(path, VaultKeyValueOperationsSupport.KeyValueBackend.KV_1);
        kvOperations.put(key, value);
    }

    /**
     * 读取指定路径的所有密钥值
     * @param path Vault 中的路径
     * @return 包含所有键值对的 Map
     */
    public Map<String, Object> readAllValues(String path) {
        VaultKeyValueOperations kvOperations = vaultTemplate.opsForKeyValue(path, VaultKeyValueOperationsSupport.KeyValueBackend.KV_1);
        VaultResponse response = kvOperations.get("");
        if (response != null) {
            return response.getData();
        }
        return null;
    }

    /**
     * 删除指定路径的密钥值
     * @param path Vault 中的路径
     * @param key 键名
     */
    public void deleteValue(String path, String key) {
        VaultKeyValueOperations kvOperations = vaultTemplate.opsForKeyValue(path, VaultKeyValueOperationsSupport.KeyValueBackend.KV_1);
        kvOperations.delete(key);
    }
}
